#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : zaniu(zzaniu@126.com)
# @Time   : 2021/6/23 14:51 
# @Desc   :
# 
#                   _ooOoo_
#                  o8888888o
#                  88" . "88
#                  (| -_- |)
#                  O\  =  /O
#               ____/`---'\____
#             .'  \\|     |//  `.
#            /  \\|||  :  |||//  \
#           /  _||||| -:- |||||-  \
#           |   | \\\  -  /// |   |
#           | \_|  ''\---/''  |   |
#           \  .-\__  `-`  ___/-. /
#         ___`. .'  /--.--\  `. . __
#      ."" '<  `.___\_<|>_/___.'  >'"".
#     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
#     \  \ `-.   \_ __\ /__ _/   .-` /  /
# =====`-.____`-.___\_____/___.-`____.-'=====
#                   `=---='
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#             佛祖保佑       永无BUG
#
import os
from concurrent import futures
import grpc

from learn_consul.consul_test_001 import register_grpc, deregister
from learn_grpc_001.proto import hello_pb2_grpc, hello_pb2
from grpc_health.v1 import health_pb2, health_pb2_grpc, health


class TokenInterceptor(grpc.ServerInterceptor):
    def intercept_service(self, continuation, handler_call_details):
        print(f"请求开始, handler_call_details = {handler_call_details}")
        print(f"type = {type(handler_call_details.invocation_metadata)}")
        if handler_call_details.method == "/grpc.health.v1.Health/Check":
            return continuation(handler_call_details)
        for k, v in handler_call_details.invocation_metadata:
            if k == "token" and v == "bt 123456789":
                break
        else:
            raise Exception("token 错误")
        rsp = continuation(handler_call_details)
        print("请求结束")
        return rsp


class Greeter(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        print(f"context.invocation_metadata() = {context.invocation_metadata()}， type = {type(context.invocation_metadata())}")
        for k, v in context.invocation_metadata():
            print(f"k = {k}, v = {v}")
        return hello_pb2.HelloReply(message='Hello, %s!' % request.name)


class AddServer(hello_pb2_grpc.AddServerServicer):
    def __init__(self):
        self.a = 0

    def AddInt(self, request, context):
        print(f"request = {request}, context = {context}")
        # context.set_code(grpc.StatusCode.CANCELLED)
        # context.set_details("沙雕啊")
        return hello_pb2.AddIntReply(message=request.value1 + request.value2)

    def AddFloat(self, request, context):
        return hello_pb2.AddFloatReply(message=request.value1 + request.value2)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=os.cpu_count()), interceptors=(TokenInterceptor(),))
    hello_pb2_grpc.add_AddServerServicer_to_server(AddServer(), server)
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    # 注册健康检查机制
    health_pb2_grpc.add_HealthServicer_to_server(health.HealthServicer(), server)
    address = "172.18.2.184"
    port = 50051
    server.add_insecure_port(f'{address}:{port}')
    register_grpc("gRPC-test", ["gprc", "test"], address, port)
    server.start()
    server.wait_for_termination()
    deregister("gRPC-test")


if __name__ == '__main__':
    serve()
